package IT.HXL.Controller;

import IT.HXL.domain.Administrators;
import IT.HXL.domain.PageBean;
import IT.HXL.domain.User;
import IT.HXL.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;


import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;

import java.util.List;
import java.util.Map;
import java.util.Random;

@Controller
public class MyController {
    @Autowired
    private UserService service;

    @RequestMapping(value = "/addUserServlet")
    public void AddUserServlet(User user, HttpServletResponse response, HttpServletRequest request) throws IOException {
        service.addUser(user);
        response.sendRedirect(request.getContextPath() + "/userListServlet");

    }

    @RequestMapping(value = "/checkCodeServlet")
    public void CheckCodeServlet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //服务器通知浏览器不要缓存
        response.setHeader("pragma", "no-cache");
        response.setHeader("cache-control", "no-cache");
        response.setHeader("expires", "0");
        //在内存中创建一个长80，宽30的图片，默认黑色背景
        //参数一：长
        //参数二：宽
        //参数三：颜色
        int width = 80;
        int height = 30;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        //获取画笔
        Graphics g = image.getGraphics();
        //设置画笔颜色为灰色
        g.setColor(Color.GRAY);
        //填充图片
        g.fillRect(0, 0, width, height);

        //产生4个随机验证码，12Ey
        String checkCode = getCheckCode();
        //将验证码放入HttpSession中
        request.getSession().setAttribute("CHECKCODE_SERVER", checkCode);

        //设置画笔颜色为黄色
        g.setColor(Color.YELLOW);
        //设置字体的小大
        g.setFont(new Font("黑体", Font.BOLD, 24));
        //向图片上写入验证码
        g.drawString(checkCode, 15, 25);

        //将内存中的图片输出到浏览器
        //参数一：图片对象
        //参数二：图片的格式，如PNG,JPG,GIF
        //参数三：图片输出到哪里去
        ImageIO.write(image, "PNG", response.getOutputStream());
    }

    /**
     * 产生4位随机字符串
     */
    private String getCheckCode() {
        String base = "0123456789ABCDEFGabcdefg";
        int size = base.length();
        Random r = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 1; i <= 4; i++) {
            //产生0到size-1的随机值
            int index = r.nextInt(size);
            //在base字符串中获取下标为index的字符
            char c = base.charAt(index);
            //将c放入到StringBuffer中去
            sb.append(c);
        }
        return sb.toString();
    }

    @RequestMapping(value = "/deleteSelectedServlet")
    public void DelSelectedServlet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //1.获取所有id
        String[] ids = request.getParameterValues("uid");
        //2.调用service删除
        service.delSelectedUser(ids);
        //3.跳转查询所有Servlet
        response.sendRedirect(request.getContextPath() + "/userListServlet");
    }

    @RequestMapping(value = "/delUserServlet")
    public void DelUserServlet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //1.获取id
        String id = request.getParameter("id");
        //2.调用service删除
        service.deleteUser(id);
        //3.跳转到查询所有Servlet
        response.sendRedirect(request.getContextPath() + "/userListServlet");
    }

    @RequestMapping(value = "/findUserServlet")
    public void FindUserServlet(String id, HttpServletResponse response, HttpServletRequest request) throws ServletException, IOException {

        //2.调用Service查询
        User user = service.findUserById(id);

        //3.将user存入request
        request.setAttribute("user", user);
        //4.转发到update.jsp
        request.getRequestDispatcher("/update.jsp").forward(request, response);
    }

    @RequestMapping(value = "/loginServlet")
    public void LoginServlet(HttpServletRequest request, Administrators administrators, HttpServletResponse response) throws ServletException, IOException {

        //2.获取数据
        //2.1获取用户填写验证码
        String verifycode = request.getParameter("verifycode");

        //3.验证码校验
        HttpSession session = request.getSession();
        String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");
        session.removeAttribute("CHECKCODE_SERVER");//确保验证码一次性
        if (!checkcode_server.equalsIgnoreCase(verifycode)) {
            //验证码不正确
            //提示信息
            request.setAttribute("login_msg", "验证码错误！");
            //跳转登录页面
            request.getRequestDispatcher("/login.jsp").forward(request, response);

            return;
        }
        //5.调用Service查询
        Administrators loginUser = service.login(administrators);
        //6.判断是否登录成功
        if (loginUser != null) {
            //登录成功
            //将用户存入session
            session.setAttribute("admin", loginUser.getAdminname());
            //跳转页面
            response.sendRedirect(request.getContextPath() + "/index.jsp");
        } else {
            //登录失败
            //提示信息
            request.setAttribute("login_msg", "用户名或密码错误！");
            //跳转登录页面
            request.getRequestDispatcher("/login.jsp").forward(request, response);

        }

    }

    @RequestMapping(value = "/updateUserServlet")
    public void UpdateUserServlet(HttpServletRequest request, HttpServletResponse response, User user) throws IOException {

        //4.调用Service修改
        service.updateUser(user);
        //5.跳转到查询所有Servlet
        response.sendRedirect(request.getContextPath() + "/userListServlet");
    }

    @RequestMapping(value = "/userListServlet")
    public void UserListServlet(HttpServletResponse response, HttpServletRequest request) throws ServletException, IOException {
        //1.调用UserService完成查询
        List<User> users = service.findAll();
        //2.将list存入request域
        request.setAttribute("users", users);
        //3.转发到list.jsp
        request.getRequestDispatcher("/list.jsp").forward(request, response);
    }

    @RequestMapping("/findUserByPageServlet")
    public void findUserByPage(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        request.setCharacterEncoding("utf-8");
        String currentPage = request.getParameter("currentPage");
        String rows = request.getParameter("rows");

        if (currentPage == null || "".equals(currentPage)) {
            currentPage = "1";
        }
        if (rows == null || "".equals(rows)) {
            rows = "5";
        }

        Map<String, String[]> condition = request.getParameterMap();


        PageBean<User> pb = service.findUserByPage(currentPage, rows, condition);
        System.out.println(pb);

        request.setAttribute("pb", pb);
        request.setAttribute("condition", condition);
        request.getRequestDispatcher("/listPage.jsp").forward(request, response);
    }


}
